using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdminDto.CarType.AreaDtos;
using AvalonAdminDto.CarType.CountryDtos;
using AvalonAdminDto.Common;
using D.UtilCore.Dtos;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace AvalonAdmin.Pages.CarType.ViewModels.Country
{
    /// <summary>
    /// 国家修改视图模型，专门用于国家添加和编辑功能
    /// </summary>
    public class CountryModifyViewModel : BaseModifyViewModel
    {
        #region 页面属性及初始化数据

        private string? _id;
        
        /// <summary>
        /// 地区列表
        /// </summary>
        public ObservableCollection<RepArea> AreaList { get; set; }
        
        public CountryModifyViewModel(string? id = null, ViewStatus? viewStatus = ViewStatus.Add) 
        {
            _id = id;
            SetupFormStatus(viewStatus);

            // 初始化地区列表
            AreaList = new ObservableCollection<RepArea>();
            
            // 加载地区数据
            _ = Task.Run(async () => 
            {
                await QueryAreaAsync();
                
                // 如果有ID，则加载数据
                if (!string.IsNullOrEmpty(_id))
                {
                    await QueryAsync();
                }
            });
        }
        
        /// <summary>
        /// 查询地区数据
        /// </summary>
        private async Task QueryAreaAsync()
        {
            try
            {
                var res = await HttpHelper<List<RepArea>>.GetAsync(ApiUrl.QueryAreaList);
                if (res.Code == StatusCodeEnum.OK && res.Data != null)
                {
                    AreaList.Clear();
                    foreach (var area in res.Data)
                    {
                        AreaList.Add(area);
                    }
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"加载地区数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 查询数据（用于刷新当前国家数据）
        /// </summary>
        public override async Task<bool> QueryAsync()
        {
            if (!string.IsNullOrEmpty(_id))
            {
                try
                {
                    var res = await HttpHelper<RepCountry>.GetAsync($"{ApiUrl.GetCountry}/{_id}");

                    if (res.Code == StatusCodeEnum.OK && res.Data != null)
                    {
                        //CurrentCountry = new RepCountry
                        //{
                        Name = res.Data.Name;
                        Code = res.Data.Code;
                        EnglishName = res.Data.EnglishName;
                        
                        // 加载关联的地区信息
                        if (!string.IsNullOrEmpty(res.Data.AreaId))
                        {
                            var resArea = await HttpHelper<RepArea>.GetAsync($"{ApiUrl.GetArea}/{res.Data.AreaId}");
                            if (resArea.Code == StatusCodeEnum.OK && resArea.Data != null)
                            {
                                // 在AreaList中找到对应的地区并设置为选中
                                var selectedArea = AreaList.FirstOrDefault(a => a.Id == resArea.Data.Id);
                                if (selectedArea != null)
                                {
                                    Area = selectedArea;
                                }
                            }
                        }
                    }
                    else if (res.Code == StatusCodeEnum.Waring)
                    {
                        ShowWarning(res.Msg);
                    }
                    else
                    {
                        ShowError(res.Msg ?? "加载国家数据失败");
                    }
                }
                catch (System.Exception ex)
                {
                    ShowError($"加载国家数据失败：{ex.Message}");
                }
            }
            return true;
        }
        #endregion

        #region 数据编辑属性

        private RepArea? _area;
        /// <summary>
        /// 所属地区
        /// </summary>
        [Required(ErrorMessage = "所属地区不能为空")]
        public RepArea? Area
        {
            get => _area;
            set => SetProperty(ref _area, value);
        }

        private string? name;
        /// <summary>
        /// 名称
        /// </summary>
        [Required(ErrorMessage = "名称不能为空")]
        public string? Name
        {
            get => name;
            set => SetProperty(ref name, value);
        }

        private string? code;
        /// <summary>
        /// 编码
        /// </summary>
        [Required(ErrorMessage = "编码不能为空")]
        public string? Code
        {
            get => code;
            set => SetProperty(ref code, value);
        }

        private string? englishName;
        /// <summary>
        /// 英文名
        /// </summary>
        public string? EnglishName
        {
            get => englishName;
            set => SetProperty(ref englishName, value);
        }
        #endregion

        #region 提交，重置
        /// <summary>
        /// 提交数据
        /// </summary>
        protected override async Task SubmitAsync()
        {
            try
            {
                // 验证输入参数
                if (!ValidateInput())
                {
                    return;
                }

                if (string.IsNullOrEmpty(_id))
                {
                    // 添加国家
                    var res = await HttpHelper<int>.PostAsync(ApiUrl.AddCountry, new ReqAddCountry()
                    {
                        AreaId = Area.Id,
                        Name = Name,
                        Code = Code,
                        EnglishName = EnglishName
                    });
                    HandleApiResponse(res, "添加成功", "添加失败");
                }
                else
                {
                    // 修改国家
                    var res = await HttpHelper<int>.PutAsync($"{ApiUrl.UpdateCountry}", new ReqUpdateCountry()
                    {
                        Id = _id,
                        AreaId = Area.Id,
                        Name = Name,
                        Code = Code,
                        EnglishName = EnglishName
                    });
                    HandleApiResponse(res, "修改成功", "修改失败");
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 验证输入参数
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateInput()
        {
            if (string.IsNullOrEmpty(Name))
            {
                ShowWarning("国家名称不能为空");
                return false;
            }

            if (string.IsNullOrEmpty(Code))
            {
                ShowWarning("国家编码不能为空");
                return false;
            }

            if (Area == null)
            {
                ShowWarning("请选择所属地区");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            Area = null;
            Name = null;
            Code = null;
            EnglishName = null;
        }
        #endregion 
    }
}